package org.example.service;

import cn.hutool.http.HttpRequest;
import org.example.util.RedisUtil;
import org.example.util.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.apache.commons.lang.StringUtils;

import java.util.Optional;

@Service
public class ThirdAppWechatEnterpriseService {

    @Autowired
    private WechatUtil wechatUtil;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * OAuth2登录，成功返回登录的SysUser，失败返回null
     */
    public String oauth2Login(String code)  {
        try {
            String accessToken = wechatUtil.getAppAccessToken(redisUtil);
            return Optional.ofNullable(accessToken)
                    .map(token->this.getUserIdByThirdCode(code, token))
                    .orElseThrow(()->new Exception("用户不存在"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据第三方登录获取到的code来获取第三方app的用户ID
     *
     * @param code
     * @return
     */
    public String getUserIdByThirdCode(String code, String accessToken) {
        String result = HttpRequest.get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken +
                "&code=" + code)
                .execute().body();

        //组装拼接过程
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(result);
        if ("0".equals(jsonObject.get("errcode").toString())) {
            if (StringUtils.isNotBlank(jsonObject.get("UserId").toString())) {
                return jsonObject.get("UserId").toString();
            } else if (StringUtils.isNotBlank(jsonObject.get("external_userid").toString())) {
                return jsonObject.get("external_userid").toString();
            }
        }
        return null;
    }
}
